package com.fiap.json;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;
 
public class JSONParser {
	
	//TAG used for logs
	private static final String TAG = "JSONParser";
	
	static List<NameValuePair> nameValuePairParams;
		
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
 
    // constructor
    public JSONParser() {
 
    }
 
    public JSONObject getJSONFromUrl(String url, List<NameValuePair> nameValuePairParams) {
    	
    	this.nameValuePairParams = nameValuePairParams;
 
        // Making HTTP request
        try {
            
            ExecuteHttpTask task = new ExecuteHttpTask();
    	    HttpResponse httpResponse = task.execute(url).get();
            
            Log.w(TAG, "-------------------------------- 5");
            HttpEntity httpEntity = httpResponse.getEntity();
            Log.w(TAG, "-------------------------------- 6");
            is = httpEntity.getContent();
            Log.w(TAG, "-------------------------------- 7");
 
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        Log.w(TAG, "-------------------------------- 8");
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            Log.w(TAG, "-------------------------------- 9");
            StringBuilder sb = new StringBuilder();
            Log.w(TAG, "-------------------------------- 10");
            String line = null;
            Log.w(TAG, "-------------------------------- 11");
            while ((line = reader.readLine()) != null) {
                sb.append(line + "n");
            }
            Log.w(TAG, "-------------------------------- 12");
            is.close();
            Log.w(TAG, "-------------------------------- 13");
            json = sb.toString();
            Log.w(TAG, "-------------------------------- 14. abaixo json");
            Log.e("JSON", json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
 
        // try parse the string to a JSON object
        try {
        	Log.w(TAG, "-------------------------------- 15");
            jObj = new JSONObject(json);            
            Log.w(TAG, "-------------------------------- 16");
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
 
        // return JSON String
        return jObj;
 
    }
    
    
    private class ExecuteHttpTask extends AsyncTask<String, Void, HttpResponse> {
		@Override
		protected HttpResponse doInBackground(String... params) {
			String response = "";
			String url = params[0];
			
			// defaultHttpClient
        	Log.w(TAG, "-------------------------------- 1");
            DefaultHttpClient httpClient = new DefaultHttpClient();
            Log.w(TAG, "-------------------------------- 2");
            HttpPost httpPost = new HttpPost(url);
            Log.w(TAG, "-------------------------------- 3");
            try {
				httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairParams));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            Log.w(TAG, "-------------------------------- 4");
            
            HttpResponse httpResponse = null;
			try {
				httpResponse = httpClient.execute(httpPost);
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            
			return httpResponse;
		}

	}
}